package cn.haona.game.simb.object.department;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import cn.haona.game.simb.comm.CommException;
import cn.haona.game.simb.comm.util.IllWordFilter;
import cn.haona.game.simb.object.bio.Npc;
import cn.haona.game.simb.object.bio.PersistenceHuman;
import cn.haona.game.simb.object.bio.User;
import cn.haona.game.simb.object.bio.User.UserPO;
import cn.haona.game.simb.object.god.EntityManager;
import cn.haona.game.simb.object.god.MainManager;
import cn.haona.game.simb.object.god.cache.Cache;

/**
 * 民政局
 * 
 * @author Administrator
 * 
 */
public class HAB {

	public HAB() {

	}

	/**
	 * 注册用户
	 * 
	 * @param loginName
	 * @param password
	 * @param nickName
	 * @param sex
	 * @return
	 * @throws CommException
	 */
	public User registerUser(String loginName, String password, String nickName,
			int sex) throws CommException {

		// 敏感词过滤
		IllWordFilter illWordFilterLocal = MainManager.getInstance()
				.getEntityManager().getIllWordFilterLocal();

		// 是否禁用词汇
		if (illWordFilterLocal.isIllWord(loginName)
				|| illWordFilterLocal.isIllWord(nickName)) {
			throw new CommException("10002", "禁用词汇");
		}

		Connection conn = MainManager.getInstance().getPersistenceManager()
				.getDB_Connection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			// 先看是否已经有人使用了这个用户名
			String sqlCheck = "select * from " + UserPO.TABLE_NAME + " where "
					+ UserPO.LOGINNAME + "=?";
			ps = conn.prepareStatement(sqlCheck);
			ps.setString(1, loginName);
			rs = ps.executeQuery();
			// 如果有结果
			if (rs.next()) {
				throw new CommException("10000", "已经有这个用户！");
			}

			// 持久化我
			User userPersis = new User();
			userPersis.initPO();
//			userPersis.getUserPO().persisParam(User.UserPO.LOGINNAME, name);
//			userPersis.getUserPO().persisParam(User.UserPO.PASSWORD, password);
//			userPersis.getUserPO().persisParam(User.UserPO.SEX, sex);
//			userPersis.getUserPO().persisParam(User.UserPO.NAME, nickName);
//			userPersis.getUserPO().persisParam(User.UserPO.ADDEDON, new Timestamp(System.currentTimeMillis()));
//			userPersis.getUserPO().persisParam(User.UserPO.UPDATEON, new Timestamp(System.currentTimeMillis()));
			userPersis.getUserPO().setLoginName(loginName);
			userPersis.getUserPO().setPassword(password);
			userPersis.getUserPO().setSex(sex);
			userPersis.getUserPO().setName(nickName);
			userPersis.getUserPO().setAddedDate(new Timestamp(System.currentTimeMillis()));
			userPersis.getUserPO().setUpdateDate(new Timestamp(System.currentTimeMillis()));

			Long iUserID = userPersis.getUserPO().persisMeFirstTime();

			// // INSERT INTO Store_Information (store_name, Sales, Date)
			// // VALUES ('Los Angeles', 900, 'Jan-10-1999')
			// String sql = "insert into " + User.UserPO.TABLE_NAME + " ("
			// + User.UserPO.LOGINNAME + "," + User.UserPO.PASSWORD + ","
			// + User.UserPO.NICKNAME + ","+User.UserPO.SEX+
			// ") values (?,?,?,?)";
			//
			// ps = conn.prepareStatement(sql);
			//
			// ps.setString(1, name);
			// ps.setString(2, password);
			// ps.setString(3, nickName);
			// ps.setString(4, new String(new char[]{sex}));
			// ps.execute();
			User user = (User) MainManager.getInstance().getEntityManager()
					.getCellInstance(User.class.getName(), iUserID);
			// User user = checkExistUser(name, password);
			return user;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
				if (ps != null) {
					ps.close();
				}
				if (rs != null) {
					rs.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return null;
	}

	/**
	 * 注册用户
	 * 
	 * @param name
	 * @param password
	 * @return
	 */
	public User registerUser(String name, String password) {
		try {
			Connection conn = MainManager.getInstance().getPersistenceManager()
					.getDB_Connection();
			// INSERT INTO Store_Information (store_name, Sales, Date)
			// VALUES ('Los Angeles', 900, 'Jan-10-1999')
			String sql = "insert into " + UserPO.TABLE_NAME + " ("
					+ UserPO.LOGINNAME + "," + UserPO.PASSWORD
					+ ") values (?,?)";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			ps.setString(2, password);
			ps.execute();
			ps.close();
			conn.close();

			// 如果有结果
			User user = checkExistUser(name, password);
			return user;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 是否存在该用户
	public User checkExistUser(String name, String password) {
		try {
			Connection conn = MainManager.getInstance().getPersistenceManager()
					.getDB_Connection();
			String sql = "select * from " + UserPO.TABLE_NAME + " where "
					+ UserPO.LOGINNAME + "=? and " + UserPO.PASSWORD + "=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			ps.setString(2, password);
			ResultSet rs = ps.executeQuery();
			// 如果有结果
			if (rs.next()) {
				// 得到ID
				long lID = rs.getLong(UserPO.ID);
				// 返回该用户对象
				User user = (User) MainManager.getInstance().getEntityManager()
						.getCellInstance(User.class.getName(), lID);
				return user;
			}

			rs.close();
			ps.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 找一个家伙
	 * 
	 * @param id
	 * @return
	 */
	public User lookForUser(long id) {
		User user = null;

		EntityManager em = MainManager.getInstance().getEntityManager();
		try {
			user = (User) em.getCellInstance(User.class.getName(), id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	/**
	 * 随机找一些玩家对象
	 * 
	 * @param useNum
	 * @return
	 */
	public static List<User> randomFindUsers(int useNum, Long[] exceptionIDs) {
		List<User> listUser = new ArrayList<User>();
		List<Long> listUserIDs = randomFindUserIDs(useNum, exceptionIDs);
		Iterator<Long> iteraUserID = listUserIDs.iterator();
		HAB hab = MainManager.getInstance().getEntityManager().getHab();
		while (iteraUserID.hasNext()) {
			Long lUserID = iteraUserID.next();

			User user = hab.lookForUser(lUserID);
			listUser.add(user);
		}
		return listUser;
	}

	/**
	 * 随机找一些玩家IDs
	 * 
	 * @param userNum
	 * @return
	 */
	public static List<Long> randomFindUserIDs(int userNum, Long[] exceptionIDs) {
		/*
		 * SQL随机取记录 MYSQL SELECT FROM 表名 order By rand() Limit 1
		 */
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = MainManager.getInstance().getPersistenceManager()
					.getDB_Connection();
			String strSql = "select " + UserPO.ID + " from "
					+ UserPO.TABLE_NAME + " ";

			if (exceptionIDs != null) {
				strSql += "where ";
				for (int i = 0; i < exceptionIDs.length; i++) {
					strSql += UserPO.ID + "!=" + exceptionIDs[i];
					if (i < exceptionIDs.length - 1) {
						strSql += " and ";
					}
				}
			}
			strSql += " order by rand() limit " + userNum;

			System.out.println(strSql);

			ps = conn.prepareStatement(strSql);
			rs = ps.executeQuery();
			List<Long> listUser = new ArrayList<Long>();
			while (rs.next()) {
				long lID = rs.getLong(1);
				listUser.add(lID);
			}
			return listUser;
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.close();
					conn = null;
				}
				if (ps != null) {
					ps.close();
					ps = null;
				}
				if (rs != null) {
					rs.close();
					rs = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return null;
	}

	/**
	 * 找一个家伙
	 * 
	 * @param id
	 * @return
	 */
	public Npc lookForNpc(long id) {
		Npc npc = null;

		EntityManager em = MainManager.getInstance().getEntityManager();
		try {
			npc = (Npc) em.getCellInstance(Npc.class.getName(), id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return npc;
	}

	/**
	 * 随机找一些NPC对象
	 * 
	 * @param npcNum
	 * @param jobs
	 * @param exceptJobs
	 * @param exceptionIDs
	 * @return
	 */
	public static List<Npc> randomFindNpcs(int npcNum, int[] jobs,
			int[] exceptJobs, Long[] exceptionIDs) {
		List<Npc> listNpc = new ArrayList<Npc>();

		List<Long> listNpcID = randomFindNpcIDs(npcNum, jobs, exceptJobs,
				exceptionIDs);

		Iterator<Long> iteraNpcID = listNpcID.iterator();
		while (iteraNpcID.hasNext()) {
			Long lID = iteraNpcID.next();
			try {
				Npc npc = (Npc) MainManager.getInstance().getEntityManager()
						.getCellInstance(Npc.class.getName(), lID);
				listNpc.add(npc);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return listNpc;
	}

	/**
	 * 随机找到一些NPC
	 * 
	 * @param npcNum
	 * @param jobs
	 * @param exceptJobs
	 * @param exceptionIDs
	 * @return
	 */
	public static List<Long> randomFindNpcIDs(int npcNum, int[] jobs,
			int[] exceptJobs, Long[] exceptionIDs) {

		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		// NPC ID的列表
		List<Long> listNpcID = new ArrayList<Long>();
		try {
			String strSQL = "select " + Npc.NpcPO.ID + " from "
					+ Npc.NpcPO.TABLE_NAME + " ";

			if (jobs != null || exceptJobs != null || exceptionIDs != null) {
				strSQL += "where (";
			}

			// 必须有的职业
			if (jobs != null) {
				for (int i = 0; i < jobs.length; i++) {
					strSQL += Npc.NpcPO.JOB + "=" + jobs[i] + " ";
					if (i < jobs.length - 1) {
						strSQL += "or ";
					}
				}
			}
			// 不要的职业
			if (exceptJobs != null) {
				// 已经有职业了
				if (jobs != null) {
					strSQL += "and ";
				}
				
				for (int i = 0; i < exceptJobs.length; i++) {
					strSQL += PersistenceHuman.JOB + "!=" + exceptJobs[i] + " ";
					if (i < exceptJobs.length - 1) {
						strSQL += "and ";
					}
				}
			}
			if (jobs != null || exceptJobs != null || exceptionIDs != null) {
				strSQL += ") ";
			}

			// 不要的ID
			if (exceptionIDs != null) {
				// 已经有职业了
				if (jobs != null || exceptJobs != null) {
					strSQL += "and ";
				}

				for (int i = 0; i < exceptionIDs.length; i++) {
					strSQL += Npc.NpcPO.ID + "!=" + exceptionIDs[i] + " ";
					if (i < exceptionIDs.length - 1) {
						strSQL += "and ";
					}
				}
			}
			// 限制人数
			strSQL += " order by rand() limit " + npcNum;

			System.out.println("sql=" + strSQL);
			conn = MainManager.getInstance().getPersistenceManager()
					.getDB_Connection();
			ps = conn.prepareStatement(strSQL);
			rs = ps.executeQuery();
			while (rs.next()) {
				listNpcID.add(rs.getLong(1));
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.close();
					conn = null;
				}
				if (ps != null) {
					ps.close();
					ps = null;
				}
				if (rs != null) {
					rs.close();
					rs = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return listNpcID;
	}

}
